import CryptoJS from "crypto-js";

export default class EncryptUtil {
  constructor() {
    this.defalutKey = "LQUGb0Nqp0wY";
  }

  // aes加密
  encrypt(randomNum, plaintText) {
    const staticKey = process.env.VUE_APP_ENCRYPT_KEY || this.defalutKey;
    var key = staticKey + randomNum; //组合key
    var ikey = CryptoJS.enc.Utf8.parse(
      CryptoJS.MD5(key).toString().substring(0, 16)
    );
    var encryptedData = CryptoJS.AES.encrypt(plaintText, ikey, {
      iv: ikey,
      mode: CryptoJS.mode.CBC,
    });
    var encryptedBase64Str = encryptedData.toString();
    return encryptedBase64Str;
  }

  //解密

  decrypt(randomNum, encryptedBase64Str) {
    const staticKey = process.env.VUE_APP_ENCRYPT_KEY || this.defalutKey;
    var key = staticKey + randomNum; //组合key
    var ikey = CryptoJS.enc.Utf8.parse(
      CryptoJS.MD5(key).toString().substring(0, 16)
    );
    var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, ikey, {
      iv: ikey,
      mode: CryptoJS.mode.CBC,
    });
    var decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedData);
    return decryptedStr;
  }
}
